﻿using Service.src.Model.Folw;
using Service.src.NW.Enum;
using Service.src.NW.Model.Drive;
using Service.src.NW.Model.Enum;
using Service.src.NW.Model;
using Service.src.NW.Model.Folw;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Service.src.Flow.Server;
using System.Threading;

namespace Service.src.NW.Processor.Core
{
    public class GlobalParamProcessor : BaseProcessor
    {
        public static GlobalParamService ParamServer;

        public GlobalParamProcessor()
        {
            ParamServer = new GlobalParamService();
        }

        internal static void Run(NodeProcessor nodeProcessor, NodeInputParam input)
        {
            if (ParamServer == null)
            {
                GlobalParamProcessor processor = new GlobalParamProcessor();
            }
            Exception ErrorMessage = null;
            NodeStatusEnum Status = NodeStatusEnum.SUCCESS;
            foreach (NodeInputPlcWriteParam write in input.NodePLC.WriteParams)
            {
                if (string.IsNullOrEmpty(write.DataSource.ToString())
                   ||
                   ( write.DataSource != DeviceTypeEnum.CUSTOM_PARAM && (write.DataSourceId <= 0 || write.AddressId <= 0)))
                {
                    if (Status == NodeStatusEnum.SUCCESS)
                    {
                        Status = NodeStatusEnum.ERROR;
                    }
                    SendNodeLoggerError(nodeProcessor, $"{nodeProcessor.id}参数配置异常,未配置需要更新的参数 ", RuntimeErrorCodeEnum.NODE_INPUT_PARAM_NULL);
                    continue;
                }
                write.Content = GetNodeInputParamValue(nodeProcessor, write);
                GlobalParamEntity globalParam = new GlobalParamEntity();
                globalParam.Id = write.AddressId;
                globalParam.Value = write.Content + "";
                //Thread.Sleep(1001);
                try
                {
                    globalParam = GlobalParamService.UpdateGlobalParam(globalParam.Id, globalParam.Value);
                }
                catch (Exception ex)
                {
                    Status = NodeStatusEnum.ERROR;
                    ErrorMessage = ex;
                }
            }
            if (Status == NodeStatusEnum.SUCCESS)
            {
                SendNodeLoggerInfo(nodeProcessor, $"更新全局变量成功：", RuntimeErrorCodeEnum.NODE_INPUT_PARAM_NULL);
            }
            else {
                SendNodeLoggerError(nodeProcessor,
                            $"更新全局变量失败，原因：{ErrorMessage?.Message}", RuntimeErrorCodeEnum.NODE_INPUT_PARAM_NULL);
            }
            Complete(nodeProcessor, Status);
        }
    }
}
